<?php
namespace App\Http\Controllers;

use App\Models\Wxuser;
use Illuminate\Support\Facades\Cache;

class WxBaseController extends Controller{
    protected $appid;
    protected $secret;
    protected $token;
    protected $authToken;
    protected $minutes;
    protected $except=['login','index'];
    public function openid(){
        return $this->auth()->openid;
    }

    public function __construct(){
        $this->appid = config('appid');
        $this->secret = config('secret');
        $this->token = request()->header('token');
        $this->minutes = 10800;
        $this->middleware('checkToken')->except($this->except);
    }
    public function get_openid($code){
        // 调用微信服务器接口获取用户openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appid . "&secret=" . $this->secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($ch);
        if (empty($data)){
            return "error:". curl_error($ch);
        }else{
            curl_close($ch);
            return json_decode($data,true);
        }
    }
    public function dologin($info){
        $wxUser = Wxuser::create($info);
        return $wxUser;
    }

    public function firstLogin($openid){
        $userInfo = Wxuser::where('openid',$openid)->get();
        return $userInfo->isEmpty()?true:false;
    }

    public function generateToken($openid){
        $token = md5(time().$openid);
        Cache::add($openid,$token, $this->minutes);
        return $token;
    }
    public function refreshToken($openid){
        $token = md5(time().$openid);
        $user=Wxuser::where('openid', $openid)->first();
        $user->token=$token;
        if(Cache::has($openid)){
            Cache::forget($openid);
        }
        Cache::put($openid,$token,$this->minutes);
        return $user->save()?$token:false;
    }
    public function hasToken(){
       return $this->token!=null;
    }

    public  function auth($openid=null){
        if($openid!=null){
            return Wxuser::where('openid',$openid)->first();
        }else{
            return Wxuser::where('token',$this->token)->first();
        }
    }
}